import paramiko
import time

# SSH 连接配置
hostname = "172.16.31.108"
port = 22
username = "root"
password = "123456"
gdbserver_command = "gdbserver :3000 oled"

# SSH 连接并运行 gdbserver


def run_gdbserver(hostname, port, username, password, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, port, username, password)

    # 创建一个交互式的 shell 会话
    channel = client.invoke_shell()

    # 发送 gdbserver 命令
    channel.send(command + "\n")

    # 读取命令输出（调整等待时间和读取频率根据需要）
    time.sleep(1)  # 等待命令执行
    output = channel.recv(65535).decode("utf-8")
    print(output)

    # 保持会话打开，定期读取输出
    try:
        while True:
            if channel.recv_ready():
                output = channel.recv(65535).decode("utf-8")
                print(output)
            time.sleep(1)
    except KeyboardInterrupt:
        print("Interrupted by user")

    # 关闭会话
    channel.close()
    client.close()


# 主程序入口
if __name__ == "__main__":
    run_gdbserver(hostname, port, username, password, gdbserver_command)
